package com.aos.erp.gov.ex.utils;

import com.aos.erp.common.exception.BizException;
import com.aos.erp.gov.ex.GovConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * 对HTTPClient的封装
 */
@Slf4j
public class HttpClientUtil {

    private static final String ENCODING = "UTF-8";
    private static int timeout = 20000;//20秒

    private static HttpClient client = null;
    private static SchemeRegistry schemeRegistry; // 协议控制
    private static PoolingClientConnectionManager ccm; // HttpClient连接池(多连接的线程安全的管理器)

    static {
        try {
            /*
             * 与https请求相关的操作
             */
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null,
                    new TrustManager[]{getMyX509TrustManager()},
                    new SecureRandom());
            SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext);
            /*
             * 定义访问协议
             */
            schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));// http
            schemeRegistry.register(new Scheme("https", 443, socketFactory));// https
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }


        // 连接池管理
        ccm = new PoolingClientConnectionManager(schemeRegistry);
        ccm.setDefaultMaxPerRoute(20);//每个路由的最大连接数
        ccm.setMaxTotal(400);//最大总连接数

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);//连接超时时间（ms）
        httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);//操作超时时间（ms）
        httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);//设置http1.1或http1.0

        client = new DefaultHttpClient(ccm, httpParams);// 一个客户端就有一个连接池
    }

    /**
     * get请求
     *
     * @param url       请求URL
     * @param paramMap  请求参数
     * @param headerMap 请求头信息
     */
    public static String get(String url,
                             Map<String, String> paramMap,
                             Map<String, String> headerMap) throws BizException {
        // 拼接URL与参数
        if (MapUtils.isNotEmpty(paramMap)) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (String key : paramMap.keySet()) {
                params.add(new BasicNameValuePair(key, paramMap.get(key)));
            }
            String queryString = URLEncodedUtils.format(params, ENCODING);
            if (url.indexOf("?") > -1) {// 存在?，表示这时的URL已经带参数了
                url += "&" + queryString;
            } else {
                url += "?" + queryString;
            }
        }

        HttpGet httpGet = new HttpGet(url);

        // 设置头信息
        if (MapUtils.isNotEmpty(headerMap)) {
            Set<String> keySet = headerMap.keySet();
            for (String key : keySet) {
                httpGet.addHeader(key, headerMap.get(key));
            }
        }

        String result = "";
        HttpResponse response = null; // 发出get请求
        try {
            response = client.execute(httpGet);
        } catch (IOException e) {
            throw new BizException(600, "网络错误");
        }


        try {
            result = checkResponseStatus(url, response);
        } catch (BizException ex) {
            throw ex;
        } finally {
            httpGet.abort();// 中止请求，连接被释放回连接池
        }

        return result;
    }

    /**
     * post请求
     *
     * @param url       请求URL
     * @param paramMap  请求参数
     * @param headerMap 请求头信息
     */
    public static String post(String url,
                              Map<String, String> paramMap,
                              Map<String, String> headerMap) throws BizException {
        HttpPost httpPost = new HttpPost(url);

        // 处理参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        if (MapUtils.isNotEmpty(paramMap)) {
            Set<String> keySet = paramMap.keySet();
            for (String key : keySet) {
                params.add(new BasicNameValuePair(key, paramMap.get(key)));
            }
        }

        // 设置头信息
        if (MapUtils.isNotEmpty(headerMap)) {
            Set<String> keySet = headerMap.keySet();
            for (String key : keySet) {
                httpPost.addHeader(key, headerMap.get(key));
            }
        }

        String result = "";
        HttpResponse response = null;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params, ENCODING));// 设置参数
            response = client.execute(httpPost);
        } catch (IOException e) {
            throw new BizException(GovConstants.NETWORK_ERROR, "网络错误");
        }

        try {
            result = checkResponseStatus(url, response);
        } catch (BizException ex) {
            throw ex;
        } finally {
            httpPost.abort();// 中止请求，连接被释放回连接池
        }

        return result;
    }


    private static String checkResponseStatus(String url, HttpResponse response) throws BizException {
        String result = "";
        StatusLine status = response.getStatusLine(); // 获取返回的状态码
        HttpEntity entity = response.getEntity(); // 获取响应内容
        if (status.getStatusCode() == HttpStatus.SC_OK) { // 200
            try {
                result = EntityUtils.toString(entity, ENCODING);
            } catch (IOException e) {
                throw new BizException(GovConstants.READ_ERROR, "body读取失败");
            }
        } else if (status.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                || status.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            //如果是重定向到login界面，说明cookie过期了
            Header head = response.getFirstHeader("location");
            log.error("业务地址发生了变化", url + " 跳转到：" + head.getValue());
            if (head != null && head.getValue().indexOf("login") > 0) {
                throw new BizException(GovConstants.NEED_LOGIN, "需要登录");
            }
            throw new BizException(302, "业务地址发生了变化");
        } else {
            throw new BizException(status.getStatusCode(), "");
        }

        return result;

    }

    /**
     * 构建自定义信任管理器内部类
     */
    private static class MyX509TrustManager implements X509TrustManager {
        /**
         * 检查客户端证书，若不信任，抛出异常
         */
        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        /**
         * 检查服务端证书，若不信任，抛出异常，反之，若不抛出异常，则表示信任（所以，空方法代表信任所有的服务端证书）
         */
        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        /**
         * 返回受信任的X509证书数组
         */
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    /**
     * 为外部类获取内部类提供方法
     */
    public static MyX509TrustManager getMyX509TrustManager() {
        return new MyX509TrustManager();
    }

    /**
     * 测试
     */
    public static void main(String[] args) {
        loadYK();
    }


    public static void loadYK() {
        try {

            Map<String, String> params = new HashMap<String, String>();
            params.put("type", "4");
            params.put("index", "4");
            params.put("ykrqstart", "2018-06-05");
            params.put("ykrqend", "2018-11-05");
            params.put("kskm", "2");
            params.put("kscx", "C1");
            params.put("ksdd", "2000446");
            params.put("xm", "");
            params.put("sfzmhm", "");

            String html = HttpClientUtil.post("http://cq.122.gov.cn/drv/yycx/train/executequery", params, getHeaderMap());

            Document doc = Jsoup.parse(html);
            Elements list = doc.select(".queryResultDiv tbody tr");
            int size = list.size();
            System.out.println(html);
            System.out.println("----------开始分析结果------------");
            for (int i = 0; i < size; i++) {
                System.out.println(list.text());
            }
        } catch (BizException e) {
            e.printStackTrace();
        }
    }

    public static void keepLive() {
        try {
            System.out.println(HttpClientUtil.get("http://cq.122.gov.cn/drv/yycx/train/query?index=1", null, getHeaderMap()));
        } catch (BizException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, String> getHeaderMap() {
        Map<String, String> header = new HashMap<String, String>();
        header.put("Host", "cq.122.gov.cn");
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
        header.put("Cookie", "td_cookie=1997340901; _uab_collina=154077609761295343709795; td_cookie=1821113605; _umdata=A502B1276E6D5FEF574641142167CEC5760E255F5F1AB1B743B0955A8810006C0BEF8C4684ACAB16CD43AD3E795C914C86816F458D0B346F4A2CB8E4B36249C2; JSESSIONID-L=d595c2f4-8dd3-41b3-8d7a-a95669a92fa8; accessToken=M2eDC2KO0FbRr8EvJiFZ4EvLonXY9YVGyMwJFYnHsW20xur/CHmf6AKQj2oE3Dhlkb7C5z/6z7kVobsxGI3bssAWlVfqJzzGApeYCA/1eKlKDt/FgWWQp8rvhrQLl/3PMo55Z3hJjwH3rhq247Uuc/M3bCcdnB7aQJfqqRAhTDMpz/L2jXFbsHPnjeQ8Veop");

        return header;
    }
}